package com.fablezj.trackgen.controller.api;

import com.fablezj.trackgen.vo.Result;
import com.fablezj.trackgen.util.Coordinate;
import com.fablezj.trackgen.util.CoordinateConvert;
import com.fablezj.trackgen.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 坐标API控制器
 *
 * @author afeey
 */
@Controller
@ResponseBody
public class CoordinateApiController {

    private static final Logger logger = LoggerFactory.getLogger(CoordinateApiController.class);

    /**
     * 坐标转换
     * @param type 转换类型
     * @param source 原坐标。格式：经度,纬度;经度,纬度;经度,纬度;....;
     * @return 转换后的坐标。格式：经度,纬度;经度,纬度;经度,纬度;....;
     * @throws IOException 异常
     */
    @RequestMapping(value = "/api/coordinate/convert")
    public Object convert(String type, String source) throws IOException {

        boolean success = false;
        String msg = "";
        Object data = null;

        List<Coordinate> targetList = new ArrayList<Coordinate>();

        source = StringUtils.clearBlank(source); //清除空白字符
        if (source.endsWith(";")) {
            source = source.substring(0, source.length() - 1);
        }
        String[] coordArray = source.split(";");
        List<Coordinate> coordinates = new ArrayList<Coordinate>();
        for (String coord : coordArray) {
            String[] xy = coord.split(",");
            Coordinate coordinate = new Coordinate();
            coordinate.setX(Double.valueOf(xy[0]));
            coordinate.setY(Double.valueOf(xy[1]));
            coordinates.add(coordinate);
        }

        if (type.equals("wgs2bd09")) {
            targetList = CoordinateConvert.wgs2bd09(coordinates);
        } else if (type.equals("wgs2utm")) {
            targetList = CoordinateConvert.wgs2utm(coordinates);
        } else if (type.equals("utm2wgs")) {
            targetList = CoordinateConvert.utm2wgs(coordinates);
        }
        success = true;
        msg = "转换成功";
        data = targetList;

        // 返回结果
        Result result = new Result(success, msg, data);
        return result;
    }
}
